package com.googlecode.olabs.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import junit.framework.TestCase;

public class CollectionComparator {

	public static boolean compareContents(Collection<String> col1,
			Collection<String> col2) {
		return compareContents(col1, col2, null);
	}

	public static void assertContentsEqual(String message,
			Collection<String> expected, Collection<String> actual) {
		compareContents(expected, actual, message);
	}

	private static boolean compareContents(Collection<String> expected,
			Collection<String> actual, String assertMessage) {
		List<String> list1 = new ArrayList<String>(expected);
		List<String> list2 = new ArrayList<String>(actual);

		for (String string : list1) {
			if (!list2.remove(string)) {
				if (assertMessage != null) {
					TestCase.fail(assertMessage
							+ " - Expected but didn't find '" + string + "'");
				}
				return false;
			}
		}
		if (list2.isEmpty()) {
			return true;
		}

		if (assertMessage != null) {
			StringBuffer result = new StringBuffer();
			for (String string : list2) {
				result.append("'");
				result.append(string);
				result.append("' ");
			}
			TestCase.fail(assertMessage + " - Unexpected lines: "
					+ result.toString());
		}
		return false;
	}
}
